package com.example.employeemanagement.service.impl;

import com.example.employeemanagement.entry.Employee;
import com.example.employeemanagement.mapper.EmployeeMapper;
import com.example.employeemanagement.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private EmployeeMapper employeeMapper;

    // 使用项目外部目录存储文件，避免重启项目才能访问的问题
    private final String AVATAR_UPLOAD_DIR = "D:\\employee-avatars" + File.separator;
    // 修改访问路径，与 FileController 中的路径一致
    private final String AVATAR_ACCESS_PATH = "/files/avatar/view/";

    @Override
    public String uploadAvatar(MultipartFile file, Integer employeeId) {
        // 检查员工是否存在
        Optional<Employee> employeeOptional = employeeMapper.getEmployeeById(employeeId);
        if (employeeOptional.isEmpty()) {
            throw new IllegalArgumentException("员工不存在，ID: " + employeeId);
        }

        try {
            // 确保目录存在
            File uploadDir = new File(AVATAR_UPLOAD_DIR);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 获取文件扩展名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }

            // 使用时间戳生成唯一文件名
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
            String timestamp = dateFormat.format(new Date());
            String newFilename = "avatar_" + employeeId + "_" + timestamp + fileExtension;
            Path filePath = Paths.get(AVATAR_UPLOAD_DIR + newFilename);

            // 保存文件
            Files.copy(file.getInputStream(), filePath);

            // 更新员工头像路径
            String avatarPath = AVATAR_ACCESS_PATH + newFilename;
            employeeMapper.updateEmployeeAvatar(employeeId, avatarPath);

            return avatarPath;
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败: " + e.getMessage(), e);
        }
    }
}